package array.easy;

import java.util.HashMap;

/**
 * @author wangtianqi
 * 面试题 01.02. 判定是否互为字符重排
 */
public class CheckPermutation {
    public static void main(String[] args) {
        String s = "aab";
        String s2 = "bab";
        System.out.println(MyCode1(s, s2));

    }

    /**
     * 每次比较都会创建一个新的字符串，速度和空间都没优势
     * @param s1
     * @param s2
     * @return
     */
    public static boolean MyCode(String s1, String s2) {

        if (s1.length() != s2.length()) {
            return false;
        }

        if (s1.equals(s2)) {
            return true;
        }

        StringBuffer sb1 = new StringBuffer(s1);

        for (int i = 0; i < s1.length(); i++) {
            int temp = sb1.indexOf(s2.charAt(i) + "");
            if (temp != -1) {
                sb1.deleteCharAt(temp);
            }
        }
        return sb1.length() == 0;
    }

    /**
     * 比较每个字符出现的次数
     * @param s1
     * @param s2
     * @return
     */
    public static boolean MyCode1(String s1, String s2) {
        int length = s1.length();
        if (length != s2.length()) {
            return false;
        }

        if (s1.equals(s2)) {
            return true;
        }

        HashMap<Character, Integer> map1 = new HashMap(length);
        HashMap<Character, Integer> map2 = new HashMap(length);

        for (int i = 0; i < length; i++) {
            if (map1.get(s1.charAt(i)) != null) {
                map1.put(s1.charAt(i), map1.get(s1.charAt(i)) + 1);
            } else {
                map1.put(s1.charAt(i), 1);
            }

            if (map2.get(s2.charAt(i)) != null) {
                map2.put(s2.charAt(i), map2.get(s2.charAt(i)) + 1);
            } else {
                map2.put(s2.charAt(i), 1);
            }
        }
        return map1.equals(map2);
    }
    
    public static boolean MyCode() {
        return true;
    }
}
